#include "NetworkEvent.h"

namespace events {

void NetworkEvent::saveToStream(std::ostream &os) const {
	os.write(reinterpret_cast<const char*>(&_netype), sizeof(_netype));
	if (_netype != NE_GET_HOST_BY_NAME) {
		_s.saveToStream(os);
		if (_netype == NE_CONNECT)
			_ip.saveToStream(os);
	} else {
		_host.saveToStream(os);
		_ip.saveToStream(os);
	}
}

void NetworkEvent::readFromStream(std::istream &is) {
	is.read(reinterpret_cast<char*>(&_netype), sizeof(_netype));
	if (_netype != NE_GET_HOST_BY_NAME) {
		_s.readFromStream(is);
		if (_netype == NE_CONNECT)
			_ip.readFromStream(is);
	} else {
		_host.readFromStream(is);
		_ip.readFromStream(is);
	}
}


inline void NetworkEvent::writeIp(std::ostream &os) const {
	os <<  (_ip() & 0x000000ff)        << '.'
	   << ((_ip() & 0x0000ff00) >> 8)  << '.'
	   << ((_ip() & 0x00ff0000) >> 16) << '.'
	   << ((_ip() & 0xff000000) >> 24);
}


void NetworkEvent::writeDebugInfo(std::ostream &os) const {
	os << "NetworkEvent, type=";
	switch (_netype) {
		case NE_CREATE_SOCKET:
			os << "CREATE_SOCKET";
			break;
		case NE_CONNECT:
			os << "CONNECT [";
			writeIp(os);
			os << ']';
			break;
		case NE_LISTEN:
			os << "LISTEN";
			break;
		case NE_SEND:
			os << "SEND";
			break;
		case NE_SEND_TO:
			os << "SEND_TO";
			break;
		case NE_RECEIVE:
			os << "RECEIVE";
			break;
		case NE_RECEIVE_FROM:
			os << "RECEIVE_FROM";
			break;
		case NE_GET_HOST_BY_NAME:
			os << "GET_HOST_BY_NAME: ";
			_host.writeDebugInfo(os);
			os << ", ip=";
			writeIp(os);
			break;
	}
	if (_netype != NE_GET_HOST_BY_NAME) {
		os << ", socket=";
		_s.writeDebugInfo(os);
	}
	os << '\n';
}

}  // end namespace
